package com.menggudf.commom;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.menggudf.dao.AdminPermissionDao;
import com.menggudf.dao.SystemAdminDao;
import com.menggudf.model.SystemAdminModel;

public class RequestOperInterceptor extends HandlerInterceptorAdapter{
    
    private static final Logger LOGGER = LoggerFactory
            .getLogger(RequestOperInterceptor.class);
    
    @Autowired
    SystemAdminDao systemAdminDao;
    
    @Autowired
    AdminPermissionDao adminPermissionDao;
    
    Map<String,String> operationInterceptorMap;
    public Map<String, String> getOperationInterceptorMap() {
        return operationInterceptorMap;
    }

    public void setOperationInterceptorMap(
            Map<String, String> operationInterceptorMap) {
        this.operationInterceptorMap = operationInterceptorMap;
    }
    
    @Override
    @ResponseBody
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(true);
        LOGGER.debug("===========ControllerInterceptor preHandle——URI："
                + request.getRequestURI());
        String servletPath = request.getServletPath();
        SystemAdminModel systemAdminModel = (SystemAdminModel) session.getAttribute("SystemAdminModel");
        if(systemAdminModel==null){
            response.setContentType("application/Json;charset=UTF-8");
            response.setStatus(403);
            return false;
        }
        String adminCode = systemAdminModel.getAdminCode();
        if(!StringUtils.isEmpty(adminCode) && systemAdminDao.isAdmin(adminCode) && systemAdminModel.getFlag()==1){
            return true;
        }

        String oper = operationInterceptorMap.get(servletPath);
        
        if(adminPermissionDao.hasOper(adminCode,oper)){
            return true;
        }else{
            response.setContentType("application/Json;charset=UTF-8");
            response.setStatus(403);
            return false;
        }
    }
    
    

}
